package com.eightywork.life.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.eightywork.life.R;
import com.eightywork.life.adapter.TagListAdapter;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.model.Tag;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.util.FileUtil;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.util.PhotoUtil;
import com.eightywork.life.util.Util;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.umeng.analytics.MobclickAgent;

public class PostActivity extends BaseActivity implements OnClickListener{
	private ImageButton postButton, returnButton, cancelButton, submitButton,
			picButton;
	private GridView typeView;
	private TagListAdapter typeAdapter;
	private Dialog dialog;
	private ViewGroup layoutPic, appendLayout;
	private String picIds = "";
	private AsyncTask task;
	private EditText title, message;
	private ImageView forwardImageView;
	private TextView forwardNameView, forwardTitleView;
	private String forwardId, idType, forwardTitle, forwardName,
			forwardImage, forwardText, forwardAvatar;
	private CheckBox weiboButton, weixinButton, tencentButton;
	private List<File> files = new ArrayList<File>();
	private List<Tag> tagList = DataService.getTagList();
	private IWXAPI api;
	private static final String WXAPP_ID = "wxcefc86293a109c7a";
	private static final int THUMB_SIZE = 150;
	private Bundle bundle = new Bundle();
	private List<Uri> uris = new ArrayList<Uri>();
	private ArrayList list = new ArrayList();
	private boolean isFromCommunity;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_post);
		
		regToWx();
		initView();
		initData();
		ShareSDK.initSDK(this);
		
	}
	
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		if (task != null)
			task.cancel(true);
		super.onDestroy();
	}
	
	private void regToWx() {
		api = WXAPIFactory.createWXAPI(this, WXAPP_ID, true);
		api.registerApp(WXAPP_ID);
	}


	public void initDialog() {
		dialog = initDialog(R.layout.pop_post_type);
		typeView = (GridView) dialog.findViewById(R.id.gridView1);
		typeAdapter = new TagListAdapter(context, tagList);
		typeView.setAdapter(typeAdapter);
		typeView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				typeAdapter.setTagId(tagList.get(position).getTagid());
				typeAdapter.setTagName(tagList.get(position).getTagname());
				typeAdapter.notifyDataSetChanged();
			}
		});
		cancelButton = (ImageButton) dialog.findViewById(R.id.button_cancel);
		cancelButton.setOnClickListener(this);
		submitButton = (ImageButton) dialog.findViewById(R.id.button_sumit);
		submitButton.setOnClickListener(this);
	}

	private void initView() {
		initDialog();
		initHeader();
		weiboButton = (CheckBox) findViewById(R.id.sina_button);
		weixinButton = (CheckBox) findViewById(R.id.weixin_button);
		tencentButton = (CheckBox) findViewById(R.id.tencent_button);
		picButton = (ImageButton) findViewById(R.id.button_pic);
		picButton.setOnClickListener(this);
		layoutPic = (ViewGroup) findViewById(R.id.layout_pic);
		title = (EditText) findViewById(R.id.title);
		message = (EditText) findViewById(R.id.message);
		forwardImageView = (ImageView) findViewById(R.id.append_image);
		forwardNameView = (TextView) findViewById(R.id.append_name);
		forwardTitleView = (TextView) findViewById(R.id.append_title);
		appendLayout = (ViewGroup) findViewById(R.id.append_layout);
		weiboButton.setChecked(CacheService.isSyncSinaWeibo());
		weixinButton.setChecked(CacheService.isSyncWeixin());
		tencentButton.setChecked(CacheService.isSyncTencentWeibo());
	}

	private void initData() {
		isFromCommunity = getIntent().getBooleanExtra("isFromCommunity", false);
		forwardId = getIntent().getStringExtra("id");
		idType = getIntent().getStringExtra("idtype");
		forwardImage = getIntent().getStringExtra("image");
		forwardName = getIntent().getStringExtra("name");
		forwardTitle = getIntent().getStringExtra("title");
		forwardText = getIntent().getStringExtra("text");
		forwardAvatar = getIntent().getStringExtra("avatar");
		if (forwardId != null) {
			new ImageLoader(context).DisplayImage(forwardImage,
					forwardImageView, R.drawable.pic_1, 0, 0);
			forwardNameView.setText("@" + forwardName);
			forwardTitleView.setText(forwardTitle);
			appendLayout.setVisibility(View.VISIBLE);
		}

		if (!CacheService.getSpace().getVerifyType().equals("0")) {
			title.setFocusable(true);
			title.setHint("为了让帖子更醒目，加一个标题吧~");
		} else {
			title.setFocusable(false);
			title.setHint("业主认证成功才能发标题的亲~");
		}
	}

	@Override
	protected void onActivityResult(int requsetCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requsetCode) {
			case PhotoUtil.PHOTO_PICKED_WITH_DATA:
				File file = FileUtil.saveFile(data.getData(),
						PhotoUtil.getPackName(context), "temp", context);
				addPicView(Uri.fromFile(file));
				break;
			case PhotoUtil.CAMERA_WITH_DATA:
				addPicView(Uri.fromFile(PhotoUtil.getSaveFile(context)));
				break;
			}
		}
		super.onActivityResult(requsetCode, resultCode, data);
	}

	private void addPicView(Uri uri) {
		final ViewGroup imageLayhout = (ViewGroup) getLayoutInflater().inflate(
				R.layout.item_image, null);
		ImageView picView = (ImageView) imageLayhout
				.findViewById(R.id.imageView1);
		Bitmap bitmap = PhotoUtil.loadPhoto(uri, context, 240, 0);
		final File file = PhotoUtil.saveBitmap(
				bitmap,
				PhotoUtil.getPhotoPath(context) + "/"
						+ System.currentTimeMillis() + ".png");
		files.add(file);
		uris.add(Uri.fromFile(file));
		picView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				layoutPic.removeView(imageLayhout);
				files.remove(file);
				uris.remove(Uri.fromFile(file));
			}
		});
		picView.setImageBitmap(bitmap);
		layoutPic.addView(imageLayhout, 0);
	}

	public void initHeader() {
		initHeader("吐 槽");
		returnButton = (ImageButton) findViewById(R.id.button_left);
		returnButton.setOnClickListener(this);
		postButton = (ImageButton) findViewById(R.id.button_right);
		postButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == returnButton) {
			finish();
		} else if (v == postButton) {
			if (validate()) {
				if (weixinButton.isChecked()) {
					shareWechat();
				}
				share();
			}
		} else if (v == cancelButton) {
			dialog.dismiss();
		} else if (v == submitButton) {
			submit(true);
		} else if (v == picButton) {
			addPicture();
		}
	}
	
//	private String buildTransaction(final String type) {
//		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
//	}

	private void shareWechat() {	
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = "http://test.lifeq.com.cn/";
		String wxTitle = title.getEditableText().toString();
		String wxText = message.getEditableText().toString();
		if (wxTitle.length() > 15) {
			wxTitle = wxTitle.substring(0, 14);
		}
		if (wxText.getBytes().length > 1000) {
			wxText = wxText.substring(0, (wxText.length()/2<500)?wxText.length()/2+1:499);
		}

		// 用WXTextObject对象初始化一个WXMediaMessage对象
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = "" + wxText;
	//	System.out.println("================>" + wxText);
		msg.description ="" + wxText;
		if (files.size() > 0) {
			String imagePath = files.get(0).getPath().toString();
			Bitmap bmp = BitmapFactory.decodeFile(imagePath);
			Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
			bmp.recycle();
			if (thumbBmp != null) {
				msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
			} else {
				Bitmap defaultBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
				msg.thumbData = Util.bmpToByteArray(defaultBmp, true);
			}
			
		} else {
			Bitmap defaultBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
			msg.thumbData = Util.bmpToByteArray(defaultBmp, true);
		}
		
		// 构造一个Req
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = "webpage" + String.valueOf(System.currentTimeMillis()); // transaction字段用于唯一标识一个请求
		req.message = msg;
		req.scene = SendMessageToWX.Req.WXSceneTimeline;
		
		// 调用api接口发送数据到微信
		api.sendReq(req);
		
	}


	private void share() {
		if (idType.equals("mtalkid")) {
			String tagid = getIntent().getStringExtra("tagid");
			task = new AddMTask().execute(tagid, title.getEditableText()
					.toString(), message.getEditableText().toString(),
					forwardId);
		} else {
			dialog.show();
		}
	}

	private boolean validate() {
		String messageString = message.getEditableText().toString();
		if (messageString.equals("")) {
			message.setError(Html.fromHtml("<font color=red>请填写吐槽内容</font>"));
			return false;
		}
		if (weiboButton.isChecked()
				&& !ShareSDK.getPlatform(context, SinaWeibo.NAME).isValid()) {
			ShareSDK.getPlatform(context, SinaWeibo.NAME).authorize();
			return false;
		}
		if (tencentButton.isChecked()
				&& !ShareSDK.getPlatform(context, TencentWeibo.NAME).isValid()) {
			ShareSDK.getPlatform(context, TencentWeibo.NAME).authorize();
			return false;
		}
		return true;
	}

	private void submit(boolean isHasClass) {
	//	System.out.println("提交了拉了拉来来来来来来来来来来来来来来来来");
		if (isHasClass && typeAdapter.getTagId().equals("")) {
			Toast.makeText(context, "请选择吐槽分类", Toast.LENGTH_LONG).show();
			return;
		}
		dialog.dismiss();
		if (weiboButton.isChecked()) {
			Platform.ShareParams sp = new SinaWeibo.ShareParams();
			sp.text = message.getEditableText().toString();
			if (files.size() > 0)
				sp.imagePath = files.get(0).toString();
			Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
			weibo.SSOSetting(true);
			weibo.share(sp);
		}
		if (tencentButton.isChecked()) {
			Platform.ShareParams sp = new TencentWeibo.ShareParams();
			sp.text = message.getEditableText().toString();
			if (files.size() > 0)
				sp.imagePath = files.get(0).toString();
			Platform weibo = ShareSDK.getPlatform(context, TencentWeibo.NAME);
			weibo.share(sp);
		}
		task = new AddTask().execute(title.getEditableText().toString(),
				message.getEditableText().toString(), typeAdapter.getTagId(), typeAdapter.getTagName());
	}

	class AddTask extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			bundle.putSerializable("title", params[0]);
			bundle.putSerializable("content",params[1]);
			bundle.putString("idtype", "post");
			bundle.putSerializable("tag", params[3]);
			if (files.size() > 0) {
				list.add(uris);
				bundle.putParcelableArrayList("uri", list);
				bundle.putInt("uriSize", uris.size());
			} else {
				bundle.putInt("uriSize", 0);
			}
			
			if (!isFromCommunity) {
				bundle.putSerializable("append_idtype", idType);
				bundle.putSerializable("append_title", (forwardTitle!=null)?forwardTitle:"");
				bundle.putSerializable("append_text", forwardText);
				bundle.putSerializable("append_name", forwardName);
				if (forwardImage!=null) {
					bundle.putSerializable("append_image", forwardImage);
				} else {
					bundle.putSerializable("append_image", "");
				}	
				bundle.putSerializable("append_avatar", forwardAvatar);
//				System.out.println("=====post==append_name=" + forwardName);
//				System.out.println("=====post=append_image==" + forwardImage);
//				System.out.println("=====post=append_avatar==" + forwardAvatar);
			} else {
				bundle.putSerializable("append_idtype", "");
			}
			
			
			try {
				for (File file : files) {
					long id = CpService.uploadphoto(file);
					picIds += id + "|";
				}
				return CpService.addtalk(params[0], params[1], params[2], "",
						"", "", picIds, forwardId, idType);
			} catch (MyHttpException e) {
				showMessage(e.getErrorMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result != null) {
				showMessage(result);	
			    Intent intent  = new Intent(DataService.Constant.FEED_SHOW_BROADCAST);
			    intent.putExtra("bundle", bundle);
		  //      System.out.println("发送post广播=====");
		        sendBroadcast(intent);
		        PostActivity.this.finish();
			}		
			
			super.onPostExecute(result);
		}
	}

	class AddMTask extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				for (File file : files) {
					long id = CpService.uploadphoto(file);
					picIds += id + "|";
				}
				return CpService.mtag(params[0], params[1], params[2],
						params[3], picIds);
			} catch (MyHttpException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result != null) {
				showMessage(result);
				PostActivity.this.finish();
			}
			super.onPostExecute(result);
		}
	}

	private void addPicture() {
		if (layoutPic.getChildCount() < 7) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setItems(new String[] { "拍照", "选择图片" },
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which) {
							case 0:
								PhotoUtil.takePhotoByCamera(context);
								break;
							case 1:
								PhotoUtil.choesePhoto(context);
								break;
							}
						}
					});
			builder.show();
		} else {
			Toast.makeText(context, "最多只能添加6张图片呀亲", Toast.LENGTH_LONG).show();
		}
	}
}
